var express = require('express');
var router = express.Router();

const Token = require('../utils/token')
const dao = require('../dao/index');
const Cache = require('../utils/cache')

/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});

/* 登录 */
router.post('/login', function(req, res, next) {
	
	let {username, password} = req.body;
	let sql = `select * from t_user where name = ? and password = ?`
	dao.query(sql, [username, password]).then(results=>{
		if(results.length) {
			let token = Token.encrypt({id:results[0].id},'15d');  //将user.id加密，设置有效期15天，返回token
			
			//将登录用户缓存，同时返回客户端
			Cache.put(token,results[0])
			res.send({
				'code': 0,
				'msg': '登录成功',
				'token': token,
				'loginUser': results[0]
			})
		} else {
			res.send({
				'code': 100002,
				'msg': '登录失败'
			})
		}
	}).catch(e=>{
		res.send(e.toString())
	})
	
});

module.exports = router;
